#include "escal.h"
#include "initializer.h"
#include <stdlib.h>
#include <iostream>
#include <QSettings>
#include <QString>
#include <QDir>
#include <QApplication>
#include <QTextStream>
using namespace Escal;

Initializer::Initializer(QObject *parent)
	:QObject(parent)
{
	connect(qApp, SIGNAL(lastWindowClosed()), this, SLOT(unInit()));
};

bool Initializer::initFolders(){
#ifdef Q_WS_X11
	escalHome = QString(getenv("HOME"));
	escalHome = escalHome + QString("/.escal");
#else
	escalHome = QString(getenv("PWD"));
#endif /* Q_WS_X11 */
	dataHome = escalHome + QString("/Cache");
	homeDir = new QDir(escalHome);
	dataDir = new QDir(dataHome);
	if(!homeDir->exists()){
		if(!homeDir->mkdir(escalHome)){
			exit(1);
		}
	}
	if(!dataDir->exists()){
		if(!dataDir->mkdir(dataHome)){
			exit(1);
		}
	}
	return true;
}

bool Initializer::initSettings(){
#ifndef Q_WS_X11
	settings = new EscalSettings("escal");
#else
	settings = new EscalSettings(escalHome + QString("/escal.conf"),
		QSettings::IniFormat);
#endif /* Q_WS_X11 */
	
        // set the default keys
	
	// set default download forlder to $HOME 
	if(settings->value("DownloadFolderList")==QVariant()){
	    	settings->setValue("DownloadFolderList",
		QStringList(QString(getenv("HOME"))));
	}
	// set default download thread number to 1
	if(settings->value("DefaultThreadNum")==QVariant()){
	    	settings->setValue("DefaultThreadNum", 1);
	}
	if(settings->value("MainWindowSize")==QVariant()){
		settings->setValue("MainWindowSize", QSize(800, 500));
	}
	QString fileName = settings->fileName();
	qDebug() << fileName << endl;  
	return true;
};

void Initializer::unInit(){
	settings->sync();	
}
